import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 单选组件
///
/// [ItemType.radio]
///
/// 结合 KqFormEntity 使用
///
/// @author 周卓
///
class KqRadioItemView extends StatefulWidget {
  final KqFormEntity entity;

  /// 单选组件单选点击回调
  final Function(KqFormEntity entity, RadioData radioData)? onRadioChanged;

  /// 选择控件点击回调
  final Function(KqFormEntity entity)? onTap;

  const KqRadioItemView(
      {Key? key, required this.entity, this.onTap, this.onRadioChanged})
      : super(key: key);

  @override
  KqRadioItemViewState createState() => KqRadioItemViewState();
}

class KqRadioItemViewState extends State<KqRadioItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: InkWell(
        onTap: () {
          TextFiledUtil.clearFocus(context);
          if (widget.entity.onTap != null) {
            widget.entity.onTap!(widget.entity);
          }
          if (widget.onTap != null) {
            widget.onTap!(widget.entity);
          }
        },
        child: Column(
          children: [
            Container(
              color: bgColor,
              padding: EdgeInsets.only(
                  right: (widget.entity.paddingHorizontal ??
                          KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .paddingHorizontal ??
                          16.r) -
                      8.r),
              child: Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                        top: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            15.r,
                        bottom: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            15.r),
                    padding: EdgeInsets.only(right: widget.entity.titleRightMargin ?? (widget.entity.title.isNotEmpty ? 40.r : 0)),
                    child: Row(
                      children: <Widget>[
                        /// 是否必填
                        Container(
                          alignment: Alignment.centerRight,
                          width: widget.entity.paddingHorizontal ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingHorizontal ??
                              16.r,
                          padding: EdgeInsets.only(right: 2.r),
                          child: Text(
                            "∗",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .mustInputFontSize ??
                                    14.sp,
                                color: widget.entity.mustInput &&
                                        widget.entity.isEditable()
                                    ? KqThemeColors.textRed
                                    : KqThemeColors.bgTransparent),
                          ),
                        ),

                        /// 标题
                        LimitedBox(
                          maxWidth: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleMaxWidth ??
                              200.r,
                          child: Text(
                            widget.entity.title,
                            style: widget.entity.titleStyle ??
                                TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .titleFontSize ??
                                        16.sp,
                                    color: widget.entity.titleColor ??
                                        KqThemeColors.text26),
                          ),
                        )
                      ],
                    ),
                  ),

                  /// 右侧按钮组
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      reverse: true,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: _renderRadioButtonList(),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            /// 分割线
            Visibility(
                visible: !widget.entity.hideDivider, child: const KqDivider())
          ],
        ),
      ),
    );
  }

  List<Widget> _renderRadioButtonList() {
    if (!widget.entity.isEditable()) {
      //非编辑模式，只显示选中按钮的文字
      for (var data in widget.entity.radioData!) {
        if (data.itemId == widget.entity.valueForSubmit) {
          return [
            Container(
              margin: EdgeInsets.only(right: 8.r),
              child: Text(
                data.item,
                style: TextStyle(
                    fontSize: KqThemeManager.instance
                            .getConfig()
                            .formConfig
                            .contentFontSize ??
                        16.sp,
                    color: KqThemeColors.text59),
              ),
            )
          ];
        }
      }
      return [];
    }
    return widget.entity.radioData
            ?.map((e) => _renderRadioButtonItem(e))
            .toList() ??
        [];
  }

  Widget _renderRadioButtonItem(RadioData data) {
    return Container(
      margin: EdgeInsets.only(left: widget.entity.btnSpacing ?? 8.r),
      child: KqInkWell(
        radius: 4.r,
        enableRipple: !data.disabled,
        onTap: () {
          if (data.disabled) {
            return;
          }
          setState(() {
            widget.entity.valueForSubmit = data.itemId;
            widget.entity.valueForShow = data.item;
            //回调
            widget.entity.onRadioChanged?.call(widget.entity, data);
            widget.onRadioChanged?.call(widget.entity, data);
          });
        },
        borderWidth: 0,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 8.r, vertical: 8.r),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                getImgPath(data, data.itemId == widget.entity.valueForSubmit),
                width: 18.r,
                height: 18.r,
                fit: BoxFit.fill,
                color: data.itemId == widget.entity.valueForSubmit
                    ? KqThemeManager.getCommonConfig().mainLightColor
                    : null,
                package: getPackageName(
                    data, data.itemId == widget.entity.valueForSubmit),
              ),
              Container(
                margin: EdgeInsets.only(left: 8.r),
                child: Text(
                  data.item,
                  style: TextStyle(
                      fontSize: KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .contentFontSize ??
                          14.sp,
                      color: widget.entity.contentColor ??
                          (data.disabled
                              ? KqThemeColors.textBF
                              : KqThemeColors.text59)),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  String? getPackageName(RadioData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath != null ? null : KqGlobal.packageName)
        : (data.unCheckedImgPath != null ? null : KqGlobal.packageName);
  }

  /// 获取图片
  String getImgPath(RadioData data, bool chosen) {
    if (data.disabled) {
      return chosen
          ? (data.checkedImgPath ?? Images.commonIcRadio16SelectedDisabled)
          : (data.unCheckedImgPath ?? Images.commonIcRadio16UnselectedEnabled);
    } else {
      return chosen
          ? (data.checkedImgPath ?? Images.commonIcRadio16SelectedEnabled)
          : (data.unCheckedImgPath ?? Images.commonIcRadio16UnselectedEnabled);
    }
  }
}

/// 单选数据
class RadioData {
  /// 显示名字
  String item;

  /// 选择后用户提交id
  String itemId;

  /// 选中的图片
  String? checkedImgPath;

  /// 未选中的图片
  String? unCheckedImgPath;

  /// 图片的包名，如果是组件库里的图片，要用[KqGlobal.packageName]
  String? package;

  /// 编辑模式下置灰且不可点击
  bool disabled;

  RadioData(
      {required this.item,
      required this.itemId,
      this.checkedImgPath,
      this.unCheckedImgPath,
      this.package,
      this.disabled = false});
}
